package br.com.avaliaprojeto.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Session;

import br.com.avaliaprojeto.model.AbstractEntity;

public abstract class AbstractDAO<T extends AbstractEntity> implements IAbstractDAO<T> {
	
	protected Class<T> currentClass = null;
	protected Session currentSession;
	
	@SuppressWarnings("unchecked")
	public AbstractDAO(Session currentSession){
		currentClass = (Class<T>)
				((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		this.currentSession = currentSession;
	}
	
	@SuppressWarnings("unchecked")
	public T findById(Integer id){
		return (T) currentSession.load(currentClass, id);
	}
	
	public T save(T entity){
		if (entity.getId() != null){
			currentSession.merge(entity);
		}else{
			currentSession.persist(entity);
		}
		
		return entity;
	}
	
	public void delete(T entity){
		currentSession.delete(entity);
	}
	
	@SuppressWarnings("unchecked")
	public List<T> list(){
		return (List<T>) currentSession.createQuery(("From " + currentClass.getName())).list();
	}
	
}
